{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Use Linkup with agents.json\n",
    "This notebook demonstrates how to use agents.json to interact with the Stripe API. This simple example shows loading the agents.json file and using it to execute Stripe tasks.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# %pip install agentsjson\n",
    "# %pip install openai"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setup API keys and references to `agents.json` files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "LINKUP_API_KEY=\"your-linkup-api-key\"\n",
    "OPENAI_API_KEY=\"your-openai-api-key\" \n",
    "agents_json_url = \"https://gist.githubusercontent.com/yagnyaPatel/41278eb9056006a8313d4e5313cf9735/raw/6c66385ec143ff4681110583de4be8ba25f7e858/linkup.agents.json\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"agentsJson\": \"0.1.0\",\n",
      "  \"info\": {\n",
      "    \"title\": \"Link Up API Integration Agents\",\n",
      "    \"version\": \"0.1.0\",\n",
      "    \"description\": \"This agents.json specification integrates with the Link Up API, which allows you to retrieve web content. It provides a flow for searching the web with different output types including sourced answers, search results, or structured data formats.\"\n",
      "  },\n",
      "  \"sources\": [\n",
      "    {\n",
      "      \"id\": \"linkup\",\n",
      "      \"path\": \"https://gist.githubusercontent.com/yagnyaPatel/670dd9fec7d101b76f92a2c4f7acfba5/raw/5fd960dfdebd35016dc285bc52aa7051576b1f66/linkup.openapi.yaml\",\n",
      "      \"description\": \"The Link Up OpenAPI specification covering web search and content retrieval functionality.\"\n",
      "    }\n",
      "  ],\n",
      "  \"overrides\": [],\n",
      "  \"flows\": [\n",
      "    {\n",
      "      \"id\": \"linkup_search_flow\",\n",
      "      \"title\": \"Search the Web\",\n",
      "      \"description\": \"Retrieves web content based on a natural language query. Can return results in different formats: sourced answers with citations, search results, or custom structured data.\",\n",
      "      \"actions\": [\n",
      "        {\n",
      "          \"id\": \"search_action\",\n",
      "          \"sourceId\": \"linkup\",\n",
      "          \"operationId\": \"linkup_post_search\"\n",
      "        }\n",
      "      ],\n",
      "      \"links\": [\n",
      "        {\n",
      "          \"origin\": {\"actionId\": \"linkup_search_flow\", \"fieldPath\": \"parameters.q\"},\n",
      "          \"target\": {\"actionId\": \"search_action\", \"fieldPath\": \"parameters.q\"}\n",
      "        },\n",
      "        {\n",
      "          \"origin\": {\"actionId\": \"linkup_search_flow\", \"fieldPath\": \"parameters.depth\"},\n",
      "          \"target\": {\"actionId\": \"search_action\", \"fieldPath\": \"parameters.depth\"}\n",
      "        }\n",
      "      ],\n",
      "      \"fields\": {\n",
      "        \"parameters\": [\n",
      "            {\n",
      "                \"name\": \"q\",\n",
      "                \"type\": \"string\",\n",
      "                \"required\": true,\n",
      "                \"description\": \"The natural language question for which you want to retrieve context.\"\n",
      "            },\n",
      "            {\n",
      "                \"name\": \"depth\",\n",
      "                \"type\": \"string\",\n",
      "                \"required\": true,\n",
      "                \"description\": \"Defines the precision of the search. 'standard' returns results quickly; 'deep' takes longer but yields more complete results.\",\n",
      "                \"enum\": [\"standard\", \"deep\"]\n",
      "            }\n",
      "        ],\n",
      "        \"requestBody\": {},\n",
      "        \"responses\": {\n",
      "          \"success\": {\n",
      "            \"type\": \"object\",\n",
      "            \"description\": \"Search results in the requested format (sourced answer, search results, or structured data).\",\n",
      "            \"example\": {\n",
      "              \"answer\": \"Five women have been awarded the Nobel Prize in Physics: Marie Curie (1903), Maria Goeppert-Mayer (1963), Donna Strickland (2018), Andrea Ghez (2020), and Anne L'Huillier (2023).\",\n",
      "              \"sources\": [\n",
      "                {\n",
      "                  \"name\": \"List of Nobel laureates in Physics - Wikipedia\",\n",
      "                  \"url\": \"https://en.wikipedia.org/wiki/List_of_Nobel_laureates_in_Physics\",\n",
      "                  \"snippet\": \"Only five women have won the prize: Marie Curie (1903), Maria Goeppert-Mayer (1963), Donna Strickland (2018), Andrea Ghez (2020), and Anne L'Huillier (2023).\"\n",
      "                }\n",
      "              ]\n",
      "            }\n",
      "          }\n",
      "        }\n",
      "      }\n",
      "    }\n",
      "  ]\n",
      "} \n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "# Fetch the agents.json file from the provided URL\n",
    "response = requests.get(agents_json_url)\n",
    "if response.status_code == 200:\n",
    "    print(response.text)\n",
    "else:\n",
    "    raise Exception(f\"Failed to fetch agents.json file: {response.status_code}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the agents.json file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from agentsjson.core.models import Flow\n",
    "from agentsjson.core.models.bundle import Bundle\n",
    "from agentsjson.core import load_agents_json\n",
    "\n",
    "# load the agents.json file\n",
    "data: Bundle = load_agents_json(agents_json_url)\n",
    "agentsjson = data.agentsJson"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Define the Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"What time is it in New York?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from agentsjson import ToolFormat, get_tool_prompt\n",
    "\n",
    "# Format the flows data for the prompt\n",
    "flows_context = get_tool_prompt(agentsjson)\n",
    "\n",
    "# Create the system prompt\n",
    "system_prompt = f\"\"\"You are an AI assistant that helps users interact with the Linkup Web Search API.\n",
    "You have access to the following API flows:\n",
    "\n",
    "{flows_context}\n",
    "\n",
    "Analyze the user's request and use the appropriate API flows to accomplish the task.\n",
    "You must give your arguments for the tool call as Structued Outputs JSON with keys `parameters` and `requestBody`\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Configure Auth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from agentsjson.core.models.auth import AuthType, ApiKeyAuthConfig\n",
    "auth = ApiKeyAuthConfig(type=AuthType.API_KEY, key_value=LINKUP_API_KEY)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run the agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'linkup_search_flow': {'success': LinkupSourcedAnswer(answer='The current time in New York is 6:37 AM on February 27, 2025.', sources=[LinkupSource(name='Current time in New York, United States.', url='https://clocks.world/time/united-states/new-york/', snippet='The time in New York is 5 hours behind UTC and the same as in Ashburn. The current timezone in New York is Eastern Standard Time (EST). New York is currently observing Standard Time (DST) also known as winter time.\\nThe time in New York is 5 hours behind UTC and the same as in Ashburn. The current timezone in New York is Eastern Standard Time (EST). New York is currently observing Standard Time (DST) also known as winter time.\\nDaylight Saving Time in New York starts at March 9, 2025. New York uses Daylight Saving Time.'), LinkupSource(name='Current time in New York', url='https://en.true-time.com/us-ny/', snippet='Current time in New York New York — exact time with seconds online. New York — transition to winter and summer time. Like on social media. Start typing the name of the country / city where you want to know the current time. United States, New York — time is now. 23:22: 51.'), LinkupSource(name='Time in New York, New York State, United States now', url='https://time.is/New_York,_New_York_State,_United_States', snippet='The current local time in New York is 9 minutes ahead of apparent solar time. New York on the map. Location: New York State, United States; Latitude: 40.77. Longitude: -73.97; Population: 1,586,000; Elevation: 30 m; Open New York in Google Maps. The 50 largest cities in United States.'), LinkupSource(name='Current time in New York, United States. Local Time Zone. Time difference.', url='https://dayspedia.com/time/us/New_York/', snippet='Current time in New York, United States. Time zone, day length, time of sunrise and sunset, daylight saving time information.\\nDaylight Saving Time (DST) (1 hour forward): Sunday, March 9 2025 03:00 — Sunday, November 2 2025 01:00\\nBy processing this request, you will restricts Google to use your personal data. Google will only show you non-personalized ads. Non-personalized ads are based on contextual information, such as the content of our website.'), LinkupSource(name='Time in New York, United States now - Time.is', url='https://time.is/New_York', snippet='The current local time in New York is 9 minutes ahead of apparent solar time. New York on the map. Location: United States; Latitude: 40.71. Longitude: -74.01; Population: 8,804,000; Elevation: 10 m; Open New York in Google Maps. Annual average temperatures for New York 1895-2021.'), LinkupSource(name='Current local time in New York City, New York, United States ...', url='https://www.timejones.com/WorldClock/United%20States/New%20York/New%20York%20City', snippet='New York City Summer Time Zone: EDT: New York City Winter Time Zone: EST: Daylight Time Start Date: Sunday, 12 March 2023, 02:00 AM: Daylight Time End Date: Sunday, 05 November 2023, 02:00 AM: UTC Offset for DST-4 Hours: UTC Offset during winter-5 Hours: Twilights in New York City today.'), LinkupSource(name='Time in New York, United States now - Time.is', url='https://time.is/New_York', snippet='Get Time.is Ad-free! ... The IANA time zone identifier for New York is America/New_York. ... Switched to UTC -5 / Eastern Standard Time (EST). The time was set back one hour from 02:00AM to 01:00AM local time. ... Switching to UTC -4 / Eastern Daylight Time (EDT).\\nSun: ↑ 06:41AM ↓ 05:38PM (10h 57m) - More info - Make New York time default - Add to favorite locations ... Remove the ads? Get Time.is Ad-free! ... The IANA time zone identifier for New York is America/New_York. ... Switched to UTC -5 / Eastern Standard Time (EST). The time was set back one hour from 02:00AM to 01:00AM local time. ... Switching to UTC -4 / Eastern Daylight Time (EDT). The time will be set forward one hour from 02:00AM to 03:00AM local time. ... The current local time in New York is 10 minutes ahead of apparent solar time.\\nExact time now, time zone, time difference, sunrise/sunset time and key facts for New York, United States.\\nAlbuquerque Arlington Atlanta Austin Bakersfield Baltimore Boston Charlotte Chicago Colorado Springs Columbus Dallas Denver Detroit El Paso Fort Worth Fresno Houston Indianapolis Jacksonville Kansas City Las Vegas Long Beach Los Angeles Louisville Memphis Mesa Miami Milwaukee Minneapolis Nashville New York Oakland Oklahoma City Omaha Philadelphia Phoenix Portland Raleigh Sacramento San Antonio San Diego San Francisco San Jose Seattle Tucson Tulsa Virginia Beach Washington, D.C.'), LinkupSource(name='Current Local Time in New York', url='https://www.calendarlabs.com/time/current-local-time-in-new-york.html', snippet='Current local time in New York. Also find local time zone, travel information, nearest airport, currency of New York, United States,\\nNew York is a state in the Northeastern region of the United States. Time Zone EDT - Eastern Daylight Time UTC/GMT -5:00 Hours'), LinkupSource(name='Current local time in New York, New York - World Time Clock & Map', url='https://24timezones.com/usa_time/ny_bronx/new_york.php', snippet='Current local time in New York, Bronx County, New York, USA, Eastern Time Zone. Check official timezones, exact actual time and daylight savings time conversion dates in 2025 for New York, NY, United States of America - fall time change 2025 - DST to Eastern Standard Time.'), LinkupSource(name='&#x1F1FA&#x1F1F8 Current time in New York', url='https://logwork.com/current-time-in-new-york-united-states', snippet='Current time in New York actual time, New York Time Zone, Current Time in New York, GMT offset\\nAtlantaAustinBaltimoreBostonBronxBrooklynCharlotteChicagoCincinnatiClevelandColumbusDallasDenverDetroitHoustonIndianapolisJacksonvilleKansas CityLas VegasLos AngelesLouisvilleManhattanMemphisMiamiMilwaukeeMinneapolisNashvilleNew OrleansNew YorkOrlandoPhiladelphiaPhoenixPittsburghPortlandProvidenceQueensRaleighRichmondRiversideSacramentoSalt Lake CitySan AntonioSan DiegoSan FranciscoSan JoseSeattleSt.')])}}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from openai import OpenAI\n",
    "from agentsjson import execute, get_tools\n",
    "client = OpenAI(api_key=OPENAI_API_KEY)\n",
    "\n",
    "response = client.chat.completions.create(\n",
    "    model=\"gpt-4o\",\n",
    "    messages=[\n",
    "        {\"role\": \"system\", \"content\": system_prompt},\n",
    "        {\"role\": \"user\", \"content\": query}\n",
    "    ],\n",
    "    tools=get_tools(agentsjson, format=ToolFormat.OPENAI),\n",
    "    temperature=0,\n",
    "    tool_choice=\"required\"\n",
    ")\n",
    "\n",
    "response = execute(agentsjson, response, format=ToolFormat.OPENAI, auth=auth)\n",
    "\n",
    "response\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
